import React, { useState, useMemo, useRef } from 'react';
import DataTable from '@/components/base/DataTable';
import { format } from '@/utils/datetime';
import DataEdit from '@/components/base/DataEdit';
import { Button, Space, Modal, Divider } from 'antd';
import IconFont from '@/components/base/IconFont';
import DataImport, { downLoadTemplateFile } from '@/components/base/DataImport';
import { renderNumber } from '@/utils/common';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import _ from 'lodash';
import { removeKeys } from '@/services/commCRUD';
import { ygddFsChange } from '@/services/AccountDivi';
// 属性类型
type PropField = {
  /** 流程运行ID */
  frid: number;
  /** 业务类型:1对公，2储蓄，3个贷 */
  ywlx: number;
  /** 业绩变更方式:0业绩带到新部门,1业绩留到原部门其他员工,2业绩留给原部门,个人业绩算自己,3业绩按账户变更 */
  yjbd: number;
  /** 业绩变更方式选项 */
  options: API.OptionItem[];
  /** 是否离职 */
  islz: boolean;
};
const SpBmbgYjbg: React.FC<PropField> = (props) => {
  const [yjbd, setSyjbd] = useState<number>(props.yjbd);
  const [showImport, setShowImport] = useState<boolean>(false);
  const tableRef = useRef<API.TableAction>();
  const yjbdConts: API.Control[] = [
    {
      name: 'yjbd',
      label: '业绩变更方式',
      type: 'select',
      grid: 12 / 24,
      dataType: 'number',
      options: props.options,
      rules: [{ required: true, message: '变更类别' }],
    },
  ];
  const name = localStorage.getItem('sysname');
  let emplCount = 4;
  if (name === 'sh') {
    if (props.ywlx === 1 || props.ywlx === 2) {
      emplCount = 4;
    } else {
      emplCount = 2;
    }
  }
  const renderFs1 = useMemo(() => {
    const fs1Conts: API.Control[] = [
      {
        name: `emid`,
        type: 'search',
        label: `员工`,
        dataType: 'number',
        grid: 12 / 24,
        placeholder: '请输入工号或名称...',
        fetch: {
          tableName: 'User',
          searchColumns: ['No', 'Name'],
          optionTpl: 'Name',
          valueTpl: 'ID',
          isDao: true,
        },
        width: 200,
        rules: [],
      },
      {
        name: `dsvl`,
        type: 'number',
        dataType: 'number',
        label: `占比`,
        grid: 12 / 24,
        rules: [{ min: 1, max: 100, message: `占比必须在1-100之间` }],
      },
    ];
    const columns: API.Column[] = [
      {
        title: '员工号',
        dataIndex: 'emno',
        key: 'emno',
        width: 100,
        sorter: true,
        dispaly: true,
      },
      {
        title: '员工姓名',
        dataIndex: 'emnm',
        key: 'emnm',
        width: 120,
        sorter: true,
        dispaly: true,
      },
      {
        title: '部门',
        dataIndex: 'dpnm',
        key: 'dpnm',
        width: 140,
        dataType: 'string',
        sorter: true,
        dispaly: true,
      },
      {
        title: `占比(%)`,
        dataIndex: `dsvl`,
        key: `dsvl`,
        render: (data: any) => renderNumber('.2f', data),
        dataType: 'number',
        width: 100,
        sorter: true,
        dispaly: true,
      },
    ];
    const daoName = 'SpBmbgToEmps';
    const delData = () => {
      if (_.isEmpty(tableRef.current?.selKeys)) {
        return;
      }
      Modal.confirm({
        title: '提示',
        icon: <ExclamationCircleOutlined />,
        content: '您确定要删除选中的行吗？',
        onOk: () => {
          removeKeys(daoName, tableRef.current!.selKeys as any[])
            .then(function (data) {
              const count = data as number;
              if (count >= 1) {
                if (tableRef.current) {
                  tableRef.current.reload();
                }
              }
            })
            .catch(function (ex) {
              console.error('删除', daoName, '错误', ex);
            });
        },
        okText: '确认',
        cancelText: '取消',
      });
    };
    return (
      <div>
        <Space style={{ marginTop: -10, marginBottom: 10 }}>
          <DataEdit
            key="edit"
            daoName={daoName}
            keyColName="id"
            extraVals={{ spid: props.frid, ywlx: props.ywlx }}
            controls={fs1Conts}
            showType="inner"
            layout="inline"
            grid={false}
            onSumit={async () => {
              tableRef.current?.reload();
            }}
            renderButtons={(p) => {
              return [
                <Button type="default" key="rest" onClick={() => p.submit()}>
                  <IconFont type="icon-xinzeng" />
                  添加
                </Button>,
                <Button key="del" onClick={() => delData()}>
                  <IconFont type="icon-shanchu" />
                  删除
                </Button>,
              ];
            }}
          />
        </Space>
        <DataTable
          key="table"
          daoName={daoName}
          columns={columns}
          pageSize={20}
          keyColName="id"
          actionRef={tableRef}
          seeks={[
            {
              WhereItems: [
                { FieldName: 'spid', Operator: '=', FieldValues: '' + props.frid },
                { FieldName: 'ywlx', Operator: '=', FieldValues: '' + props.ywlx },
              ],
              RelationSign: 'AND',
            },
          ]}
        />
      </div>
    );
  }, [props.frid, props.ywlx]);
  const renderFs3 = useMemo(() => {
    const daoName =
      props.ywlx == 1
        ? 'SpBmbgCompAccoDivi'
        : props.ywlx == 2
        ? 'SpBmbgIndiAccoDivi'
        : 'SpBmbgIndiLoanDivi';
    const importControls: API.Control[] = [];
    const columns: API.Column[] = [];
    if (props.ywlx == 1 || props.ywlx == 2) {
      importControls.push(
        ...[
          {
            name: 'cunm',
            type: 'text' as API.ControlType,
            label: '客户名称',
            grid: 12 / 24,
            rules: [{ required: true, message: '客户名称不能为空' }],
          },
          {
            name: 'acno',
            type: 'text' as API.ControlType,
            label: '账号',
            grid: 12 / 24,
            rules: [{ required: true, message: '账号不能为空' }],
          },
          {
            name: 'bano',
            type: 'text' as API.ControlType,
            label: '子账号',
            grid: 12 / 24,
            rules: [{ required: true, message: '子账号不能为空' }],
          },
          {
            name: 'opdt',
            type: 'date' as API.ControlType,
            label: '开户日',
            grid: 12 / 24,
          },
          {
            name: 'cynm',
            type: 'text' as API.ControlType,
            label: '币种',
            grid: 12 / 24,
          },
        ],
      );
      columns.push(
        ...[
          {
            title: '客户名称',
            dataIndex: 'cunm',
            key: 'cunm',
            width: props.ywlx == 1 ? 220 : 120,
            sorter: true,
            dispaly: true,
            filter: true,
            ellipsis: true,
          },
          {
            title: '账号',
            dataIndex: 'acno',
            key: 'acno',
            width: props.ywlx == 1 ? 220 : 140,
            sorter: true,
            dispaly: true,
            filter: true,
          },
          {
            title: '子账号',
            dataIndex: 'bano',
            key: 'bano',
            width: 100,
            sorter: true,
            dispaly: true,
            filter: true,
          },
          {
            title: '开户日',
            dataIndex: 'opdt',
            key: 'opdt',
            render: (data: any) => format(data, 'yyyy-MM-dd'),
            width: 100,
            sorter: true,
            dispaly: true,
            filter: true,
          },
          {
            title: '币种',
            dataIndex: 'cynm',
            key: 'cynm',
            width: 100,
            sorter: true,
            dispaly: true,
            filter: true,
          },
        ],
      );
    } else {
      importControls.push(
        ...[
          {
            name: 'cunm',
            type: 'text' as API.ControlType,
            label: '客户名称',
            grid: 12 / 24,
            rules: [{ required: true, message: '客户名称不能为空' }],
          },
          {
            name: 'evno',
            type: 'text' as API.ControlType,
            label: '借据号',
            grid: 12 / 24,
            rules: [{ required: true, message: '账号不能为空' }],
          },
          {
            name: 'opdt',
            type: 'date' as API.ControlType,
            label: '发放日',
            grid: 12 / 24,
          },
        ],
      );
      columns.push(
        ...[
          {
            title: '客户名称',
            dataIndex: 'cunm',
            key: 'cunm',
            width: 120,
            sorter: true,
            dispaly: true,
            filter: true,
          },
          {
            title: '借据号',
            dataIndex: 'evno',
            key: 'evno',
            width: 160,
            sorter: true,
            dispaly: true,
            filter: true,
          },
          {
            title: '发放日',
            dataIndex: 'opdt',
            key: 'opdt',
            render: (data: any) => format(data, 'yyyy-MM-dd'),
            width: 110,
            sorter: true,
            dispaly: true,
            filter: true,
          },
        ],
      );
    }
    importControls.push(
      ...[
        {
          name: 'utnm',
          type: 'text' as API.ControlType,
          label: '营业网点',
          grid: 12 / 24,
        },
        {
          name: 'itnm',
          type: 'text' as API.ControlType,
          label: '科目',
          grid: 12 / 24,
        },
        {
          name: 'acbl',
          type: 'number' as API.ControlType,
          label: '余额',
          grid: 12 / 24,
        },
      ],
    );
    columns.push(
      ...[
        {
          title: '营业网点',
          dataIndex: 'utnm',
          key: 'utnm',
          width: props.ywlx == 1 ? 180 : 120,
          sorter: true,
          dispaly: true,
          filter: true,
        },
        {
          title: '科目',
          dataIndex: 'itnm',
          key: 'itnm',
          width: 180,
          sorter: true,
          dispaly: true,
          filter: true,
          ellipsis: true,
        },
        {
          title: '余额',
          dataIndex: 'acbl',
          key: 'acbl',
          render: (data: any) => renderNumber('.2f', data),
          width: 120,
          sorter: true,
          dispaly: true,
          filter: true,
        },
      ],
    );
    for (let i = 0; i < emplCount; i++) {
      const dc1: API.Control = {
        name: `emno${i + 1}`,
        type: 'text',
        label: `员工号${i + 1}`,
        dataType: 'string',
        grid: 12 / 24,
      };
      const dc2: API.Control = {
        name: `emnm${i + 1}`,
        type: 'text',
        label: `员工名${i + 1}`,
        dataType: 'string',
        grid: 12 / 24,
      };
      const dc3: API.Control = {
        name: `dsvl${i + 1}`,
        type: 'number',
        dataType: 'number',
        label: `占比${i + 1}(%)`,
        grid: 12 / 24,
        rules: [{ min: 1, max: 100, message: `占比${i + 1}必须在1-100之间` }],
      };
      importControls.push(dc1);
      importControls.push(dc2);
      importControls.push(dc3);
      columns.push(
        ...[
          {
            title: `员工号${i + 1}`,
            dataIndex: `emno${i + 1}`,
            key: `emno${i + 1}`,
            width: 120,
            sorter: true,
            dispaly: true,
            filter: true,
          },
          {
            title: `员工名${i + 1}`,
            dataIndex: `emnm${i + 1}`,
            key: `emnm${i + 1}`,
            width: 120,
            sorter: true,
            dispaly: true,
            filter: true,
          },
          {
            title: `占比${i + 1}(%)`,
            dataIndex: `dsvl${i + 1}`,
            key: `dsvl${i + 1}`,
            render: (data: any) => renderNumber('.2f', data),
            width: 120,
            sorter: true,
            dispaly: true,
            filter: true,
          },
        ],
      );
    }
    const columnControls = [...importControls];
    for (let i = 0; i < emplCount; i++) {
      const dc1: API.Control = {
        name: `oemno${i + 1}`,
        type: 'text',
        label: `原员工号${i + 1}`,
        dataType: 'string',
        grid: 12 / 24,
      };
      const dc2: API.Control = {
        name: `oemnm${i + 1}`,
        type: 'text',
        label: `原员工名${i + 1}`,
        dataType: 'string',
        grid: 12 / 24,
      };
      const dc3: API.Control = {
        name: `odsvl${i + 1}`,
        type: 'number',
        dataType: 'number',
        label: `原占比${i + 1}(%)`,
        grid: 12 / 24,
        rules: [{ min: 1, max: 100, message: `占比${i + 1}必须在1-100之间` }],
      };
      columnControls.push(dc1);
      columnControls.push(dc2);
      columnControls.push(dc3);
      columns.push(
        ...[
          {
            title: `原员工号${i + 1}`,
            dataIndex: `oemno${i + 1}`,
            key: `oemno${i + 1}`,
            width: 120,
            sorter: true,
            dispaly: true,
            filter: true,
          },
          {
            title: `原员工名${i + 1}`,
            dataIndex: `oemnm${i + 1}`,
            key: `oemnm${i + 1}`,
            width: 120,
            sorter: true,
            dispaly: true,
            filter: true,
          },
          {
            title: `原占比${i + 1}(%)`,
            dataIndex: `odsvl${i + 1}`,
            key: `odsvl${i + 1}`,
            render: (data: any) => renderNumber('.2f', data),
            width: 130,
            sorter: true,
            dispaly: true,
            filter: true,
          },
        ],
      );
    }
    const title =
      props.ywlx == 1
        ? '对公认定关系导入'
        : props.ywlx == 2
        ? '储蓄认定关系导入'
        : '个贷认定关系导入';
    return (
      <div>
        <Space style={{ marginTop: -10, marginBottom: 10 }}>
          <Button
            key="down"
            onClick={() =>
              downLoadTemplateFile(
                props.ywlx == 1
                  ? '员工公司账户关系变更'
                  : props.ywlx == 2
                  ? '员工储蓄账户关系变更'
                  : '员工个贷账户关系变更',
              )
            }
          >
            <IconFont type="icon-xiazaimoban" />
            下载导入模版
          </Button>
          <Button key="import" onClick={() => setShowImport(true)}>
            <IconFont type="icon-shujudaoru" />
            导入
          </Button>
        </Space>
        <DataTable
          key="table"
          daoName={daoName}
          columns={columns}
          controls={columnControls}
          pageSize={20}
          keyColName="ACID"
          seeks={[
            {
              WhereItems: [{ FieldName: 'spid', Operator: '=', FieldValues: '' + props.frid }],
              RelationSign: 'AND',
            },
          ]}
          title={title}
        />
        {showImport ? (
          <DataImport
            key="data_import"
            importName={daoName}
            importMode="UpdateOnly"
            keys={props.ywlx == 1 || props.ywlx == 2 ? ['spid', 'acno', 'bano'] : ['spid', 'evno']}
            daoName={daoName}
            controls={importControls}
            title={title}
            visible={showImport}
            paramVals={{ spid: '' + props.frid }}
            onVisibleChange={(show) => setShowImport(show)}
          />
        ) : undefined}
      </div>
    );
  }, [props, emplCount, showImport]);
  return (
    <div>
      <DataEdit
        key="yjbdEdit"
        controls={yjbdConts}
        showType="inner"
        layout="inline"
        grid={false}
        initVals={{ yjbd: props.yjbd }}
        renderButtons={false}
        onValuesChange={async (vals) => {
          const val = vals.yjbd;
          await ygddFsChange(props.frid, props.ywlx, val, props.islz);
          setSyjbd(val as number);
        }}
      />
      <Divider style={{ marginTop: 15, marginBottom: 15 }} />
      {yjbd === 1 ? renderFs1 : undefined}
      {yjbd === 3 ? renderFs3 : undefined}
    </div>
  );
};
export default SpBmbgYjbg;
